package alt.djudge.frontend.server.servlets.gwt;

import org.apache.log4j.Logger;

import alt.djudge.frontend.client.rpc.DJudgeGWTContestService;
import alt.djudge.frontend.client.rpc.DJudgeGWTLoginService;
import alt.djudge.frontend.server.datatypes.SessionEntry;
import alt.djudge.frontend.server.datatypes.UserEntry;
import alt.djudge.frontend.server.models.SessionsModel;
import alt.djudge.frontend.server.models.UsersModel;
import alt.djudge.frontend.server.utils.BCrypt;
import alt.djudge.frontend.shared.dto.contest.UserLoginInfo;


public class DJudgeGWTLoginServiceImpl extends DJudgeGwtRpcServlet implements DJudgeGWTLoginService
{
	private static final long serialVersionUID = 1L;
	
	private static final Logger log = Logger.getLogger(DJudgeGWTContestService.class);

	@Override
	public UserLoginInfo doLogin(String username, String password)
	{
		log.trace("Trying to log in as " + username);
		UserEntry currentUser = UsersModel.getUserByUsername(username);
		if (currentUser == null)
		{
			log.trace("No such user " + username);
			return null;
		}
		String hash = BCrypt.hashpw(password, currentUser.getSalt());
		if (hash.equals(currentUser.getHash()))
		{
			String token = SessionsModel.generateAuthToken();
			SessionEntry session = new SessionEntry();
			session.setUserId(currentUser.getId());
			session.setAuthToken(token);
			session.setIp(getThreadLocalRequest().getRemoteAddr());
			session.makePersistent();
			
			UserLoginInfo info = new UserLoginInfo();
			info.setRole(currentUser.getRole());
			info.setSessionId(token);
			info.setUserId(currentUser.getId());
			info.setUsername(currentUser.getUsername());
			return info;
		}
		else
		{
			log.trace("Error " + password + " " + currentUser.getPassword());
		}
		return null;
	}

	@Override
	public boolean doLogout(String sessionId)
	{
		//
		return true;
	}

	@Override
	public boolean doRegister(String username, String password, String email)
	{
		log.trace("Trying to register user " + username);
		UserEntry user = UsersModel.getUserByUsername(username);
		if (user != null)
		{
			log.trace("User " + username + " already present");
			return false;
		}
		user = new UserEntry();
		user.setPassword(password);
		user.setEmail(email);
		user.setUsername(username);
		String salt = BCrypt.gensalt(); 
		user.setSalt(salt);
		String hash = BCrypt.hashpw(password, user.getSalt());
		user.setHash(hash);
		log.trace("User " + username + " created with hash " + hash);
		return user.makePersistent();
	}
}
